import 'dart:convert';
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:edu_assistant/model/media_data_entity.dart';
import 'package:edu_assistant/util/http.dart';
import 'package:edu_assistant/model/file_data_entity.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mime/mime.dart';
import 'package:http_parser/http_parser.dart';
class DataService {
  /// 分页获取文件
  static Future<FileDataEntity> getFilePage(params) async {
    var response = await DioRequest.getInstance()
        .dio
        .get('/upload/filePage', queryParameters: params);
    var data = jsonDecode(response.toString());
    return FileDataEntity.fromJson(data['data']);
  }

  /// 分页获取媒体
  static Future<MediaDataEntity> getMediaPage(params) async {
    var response = await DioRequest.getInstance()
        .dio
        .get('/learn/trainCourseMedia/mediaPage', queryParameters: params);
    var data = jsonDecode(response.toString());
    return MediaDataEntity.fromJson(data['data']);
  }

  /// 上传文件
  static Future uploadFile(String filePath, Function(dynamic fileUrl) resultRecive) async {
    String? mimeType = lookupMimeType(filePath);
    if (mimeType == null) {
      return '';
    }
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        filePath,
        contentType: MediaType.parse(mimeType),
      ),
    });
    int total = 0;
    int uploaded = 0;
    Dio dio = DioRequest.getInstance().dio;
    await dio.post(
      '/upload/singleFile',
      data: formData,
      onSendProgress: (send, totalBytes) {
        total = totalBytes;
        uploaded = send;
        double progress = uploaded / total;
        if (progress >= 1.0) {
          EasyLoading.showSuccess("后台处理中");
        } else {
          EasyLoading.showProgress(
            progress,
            status: '上传进度：${(progress * 100).toInt()}%',
          );
        }
      },
    ).then((Response response) {
      // 上传成功后的处理逻辑
      print('上传成功，响应数据：${response.data}');
      EasyLoading.showSuccess("上传成功");
      resultRecive(response.data["data"]);
    }).catchError((error) {
      // 上传失败后的处理逻辑
      print('上传失败，错误信息：$error');
      EasyLoading.showError("上传失败");
    });
  }
}
